package com.tianji.promotion.utils;

import com.tianji.promotion.enums.MyLockType;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;
@Component
//使用工厂模式  进行锁的创建
public class MyLockFactory {
    //EnumMap  枚举类型的map key是枚举类型 value是枚举类型的值
    private final Map<MyLockType, Function<String, RLock>> lockHandlers= new EnumMap<>(MyLockType.class);

    public MyLockFactory(RedissonClient redissonClient){
        lockHandlers.put(MyLockType.RE_ENTRANT_LOCK, redissonClient::getLock);//可重入锁
        lockHandlers.put(MyLockType.FAIR_LOCK, redissonClient::getFairLock);//公平锁
        lockHandlers.put(MyLockType.READ_LOCK,name->redissonClient.getReadWriteLock(name).readLock());
        lockHandlers.put(MyLockType.WRITE_LOCK,name->redissonClient.getReadWriteLock(name).writeLock());
    }

    public RLock getLock(String lockName, MyLockType lockType){
        return lockHandlers.get(lockType).apply(lockName);
    }
}
